package com.cas.wict.dicttrans.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.cas.wict.common.BaseResponse;
import com.cas.wict.common.PageData;
import com.cas.wict.dicttrans.interceptor.annotation.Dict;
import com.cas.wict.dicttrans.interceptor.dao.DictMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author qiancheng@cqxyy.net
 * @date 2022/9/15
 */
@MapperScan(basePackages = {"com.cas.wict.dicttrans.interceptor"})
public class DictProcessor {
    @Autowired
    private Environment environment;
    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    DictMapper dictMapper;
    public Object toDictType(Object result) {
        String dataSource = environment.getProperty("dict-trans.dataSource");
        List<JSONObject> items = new ArrayList<>();

        //加了Dict注解的字段
        List<Field> fieldList = new ArrayList<>();

        //当Trans.DICT时将数据存入
        Map<String,List<String>> dataListMap = new HashMap<>();

        //当Trans.TABLE时将数据存入
        Map<String,List<Table>> tables = new HashMap<>();
        //Api那一步马上要返回到前端的结果集
        List<Object> records = new ArrayList<>();

        Object tmp = result;
        if(result instanceof BaseResponse){
            tmp = ((BaseResponse) result).getData();
        }
        if(tmp == null){
            return result;
        }
        if(tmp instanceof PageData){
            records = ((PageData) tmp).getData();
        }else{
            List<Object> tmp1 = new ArrayList<>();
            tmp1.add(tmp);
            records = tmp1;
        }

        //首先检测结果集中是否含有该注解
        if(!haveAnnotion((records))){
            return result;
        }
        //组装需要查询的信息
        for(Object record : records){
            String json = "";
            //将每一个响应都拆成json
            try {
                json = objectMapper.writeValueAsString(record);
            }catch (JsonProcessingException e){
                System.out.println("Json解析失败" + e.getMessage());
            }
            //将json变为json对象，顺序不变
            JSONObject item= JSONObject.parseObject(json, Feature.OrderedField);
            for(Field field : getAllFields(record)){
                if(StringUtils.isBlank(item.getString(field.getName()))){
                    continue;
                }
                //将有此注解的属性保存
                if(field.getAnnotation(Dict.class) != null){
                    //重复值不添加
                    if(!fieldList.contains(field)){
                        fieldList.add(field);
                    }
                    //获取注解信息
                    String judge = field.getAnnotation(Dict.class).type();
                    if (judge.equals("table")){
                        String table = field.getAnnotation(Dict.class).table();
                        String value = field.getAnnotation(Dict.class).value();
                        String verdict = field.getAnnotation(Dict.class).verdict();
                        if(CollectionUtils.isEmpty(tables.get(table))){
                            List<Table> tables1 = new ArrayList<>();
                            Table table1 = new Table(value,verdict,item.getString(field.getName()));
                            tables1.add(table1);
                            tables.put(table,tables1);
                        }else{
                            List<Table> tables1 = tables.get(table);
                            Table table1 = new Table(value,verdict,item.getString(field.getName()));
                            tables1.add(table1);
                            tables.put(table,tables1);
                        }
                    }
                    String colum = field.getAnnotation(Dict.class).value();
                    String text = item.getString(field.getName());
                    List<String> dataList = dataListMap.computeIfAbsent(colum,key->new ArrayList<>());
                    dataList.add(text);
                }
            }
            items.add(item);
        }

        //查询Trans.DICT信息
        List<Map<String,Object>> dictResult = dictMapper.selectDict(dataListMap,dataSource);

        //查询Trans.TABLE信息
        Map<String,List<Map<String,Object>>> tableResult = new HashMap<>();
        for(Map.Entry<String,List<Table>> entry : tables.entrySet()){
            List<Table> table = entry.getValue();
            Set<String> value_tmp = new HashSet<>();
            Map<String,List<String>> map = new HashMap<>();
            table.stream().forEach(s ->{
                value_tmp.add(s.getValue());
                if (map.get(s.getVerdict())==null){
                    List<String> list1 = new ArrayList<>();
                    list1.add(s.getText());
                    map.put(s.getVerdict(),list1);
                }else{
                    List list1 = map.get(s.getVerdict());
                    list1.add(s.getText());
                }
            });
            List<String> value = new ArrayList<>(value_tmp);
            List<Map<String,Object>> strings = dictMapper.selectTable(value,entry.getKey(),map,dataSource);
            tableResult.put(entry.getKey(),strings);
        }

        //DICT拼接查询结果
        for(JSONObject record : items){
            Map<String,String> tableMap = new HashMap<>();
            for(Field field : fieldList){
                String typeResult = "";
                if(field.getAnnotation(Dict.class).type().equals("table")){
                    String value = field.getAnnotation(Dict.class).value();
                    String table = field.getAnnotation(Dict.class).table();
                    String verdict = field.getAnnotation(Dict.class).verdict();
                    String text = record.getString(field.getName());
                    //没有查这个表，下一个循环
                    if(tableResult.get(table) == null){
                        continue;
                    }else {
                        List<Map<String,Object>> list = tableResult.get(table);
                        for(Map<String,Object> s : list){
                            //没有查这个字段，下一个循环
                            if(s.get(verdict) == null){
                                continue;
                            }else{
                                if(((String)s.get(verdict)).equals(text)){
                                    DictType dictType = new DictType(text,(String)s.get(value));
                                    typeResult = dictType.getType();
                                    break;
                                    //查询没有对应结果，下一个循环
                                }else{
                                    continue;
                                }
                            }
                        }
                    }
                }else{
                    String colum = field.getAnnotation(Dict.class).value();
                    String text = record.getString(field.getName());
                    for(Map<String,Object> s : dictResult){
                        //没有查这个字段，下一个循环
                        if(!s.get("dict_type").equals(colum)){
                            continue;
                        }else{
                            if(((String)s.get("dict_value")).equals(text)){
                                DictType dictType = new DictType(text,(String)s.get("dict_label"));
                                typeResult = dictType.getType();
                                break;
                            }else{
                                continue;
                            }
                        }
                    }
                }
                tableMap.put(field.getName() + "Name",typeResult);
            }
            record.put("dictMap",tableMap);
        }

        //拼接返回类型
        if(result instanceof BaseResponse){
            if(((BaseResponse)result).getData() instanceof PageData){
                ((PageData)((BaseResponse)result).getData()).setData(items);
                return result;
            }else {
                ((BaseResponse)result).setData(items);
                return result;
            }
        }else if(result instanceof PageData){
            ((PageData)result).setData(items);
            return result;
        }else {
            return items;
        }
    }


    //检测结果集中是否含有该注解
    public Boolean haveAnnotion(List<Object> records) {
        if(records != null && !"".equals(records) && records.size() >0){
            for(Field field : getAllFields(records.get(0))){
                if(field.getAnnotation(Dict.class) != null && !field.getAnnotation(Dict.class).equals("")){
                    return true;
                }
            }
        }
        return false;
    }

    //取出List结果集中的每个属性
    public Field[] getAllFields(Object object){
        Class<?> clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null){
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }
}
